//
//  finalViewController.m
//  finalProject
//
//  Created by Cooper "Kazel" Riehl on 7/30/12.
//  Copyright (c) 2012 SaveTheBehir Industries. All rights reserved.
//
//  TO-DO:
//  * fix the restart buttons
//
//  Ctrl+f "debug.text" to find points where debug label is used.
//  Ctrl+f "TODO" to find spots where things need to be added/changed
//  DON'T FORGET TO [[__ ALLOC] INIT] YOUR ARRAYS AND OBJECTS!!!
//  ALLOCATE AND INITIATE
//  
//  Things to remember for next time (or if you ever try to fix this code):
//
//  * images should be a part of the tower and monster classes, not separate variables (i.e should be a UIImageView in tower.h and monster.h instead of having an array of "towerImages" and "monsterImages")
//  * tower projectiles should have their own class, so that each tower can fire more than one projectile at a time (projectile *newProjectile = [[projectile alloc] init];)
//  * towers should have different ranges
//  * Different monster types/images per wave (new names for new monsters)
//  * Tower projectiles shouldn't be as jittery when firing (find a better movement algorithm for projectiles)
//  * make animations for monsters (moving and walking) and possibly towers (floating rocks around orb, swirling winds etc)
//  * upgradeable towers
//  * tower specials should actually DO stuff
//  * BALANCE the monster health per wave, number of monsters, tower damage, monster speed, etc. (will most likely come with the addition of upgading)
//  * WHY DO PROJECTILES SLOW DOWN ON THE LAST MONSTER????

#import "finalViewController.h"

@interface finalViewController ()

@end

@implementation finalViewController
@synthesize info;
@synthesize labelGold;
@synthesize livesLeft;
@synthesize waves;
@synthesize labelMonstersRemaining;
@synthesize button1;
@synthesize button2;
@synthesize button3;
@synthesize button4;
@synthesize controllerBuild;
@synthesize controllerStats;
@synthesize controllerGameOver;
@synthesize controllerPause;

- (void)viewDidLoad
{
    towers = [[NSMutableArray alloc] init];
    towerImages = [[NSMutableArray alloc] init];
    monsters = [[NSMutableArray alloc] init];
    monsterImages = [[NSMutableArray alloc] init];
    
    build = FALSE;
    globalRestart = FALSE;
    button4.hidden = FALSE;
    [button4 setTitle:@"Start" forState:UIControlStateNormal];
    button4.tag = 64;
    cG = 0;
    spawnInterval = 1.00;
    wave = 1;
    firstMonster = TRUE;
    monstersRemaining = 0;
    button1.hidden = TRUE;
    button2.hidden = TRUE;
    button3.hidden = TRUE;
    towerIsAtCurrentGridpoint = FALSE;
    towerIndex = 0;
    gold = 125;
    lives = 5;
    gameOver = FALSE;
    waveActive = FALSE;
    waveShouldBeActive = FALSE;
    monstersRemaining = 8;
    monstersCreated = 0;
    timerValue = 0;
    nextMonster = 0;
    labelGold.text = [NSString stringWithFormat:@"%d",gold];
    livesLeft.text = [NSString stringWithFormat:@"Lives: %d",lives];
    waves.text = [NSString stringWithFormat:@"Wave: %d",wave];
    labelMonstersRemaining.text = [NSString stringWithFormat:@"Monsters remaining: %d",monstersRemaining];
    float x=0, y=120;
    xcoord = [[NSMutableArray alloc] init];
    ycoord = [[NSMutableArray alloc] init];
    for (int i=0; i<56; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        button.frame = CGRectMake(x, y, 40, 40);
        button.tag = i;
        [button addTarget:self action:@selector(buttonPress:) forControlEvents:UITouchPhaseEnded];
        [button setTitle:[NSString stringWithFormat:@"%d",button.tag] forState:UIControlStateNormal];
        [xcoord addObject:[NSNumber numberWithFloat:x]];
        [ycoord addObject:[NSNumber numberWithFloat:y]];
        x+=40;
        if (x==320) {
            x=0;
            y+=40;
        }
        [self.view addSubview:button];
    }
    x=0;
    y=120;
    for (int i=0; i<56; i++) {
        if (x==160 && y<=220) {
            UIImageView *imageGrid = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, 40, 40)];
            imageGrid.backgroundColor = [UIColor brownColor];
            [self.view addSubview:imageGrid];
        } else if (x<=160 && x>=80 && y>=180 && y<=220) {
            UIImageView *imageGrid = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, 40, 40)];
            imageGrid.backgroundColor = [UIColor brownColor];
            [self.view addSubview:imageGrid];
        } else if (x==80 && y>=220 && y<=340) {
            UIImageView *imageGrid = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, 40, 40)];
            imageGrid.backgroundColor = [UIColor brownColor];
            [self.view addSubview:imageGrid];
        } else if (x>=80 && x<=240 && y>=300 && y<=340) {
            UIImageView *imageGrid = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, 40, 40)];
            imageGrid.backgroundColor = [UIColor brownColor];
            [self.view addSubview:imageGrid];
        } else if (x==240 && y>=340) {
            UIImageView *imageGrid = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, 40, 40)];
            imageGrid.backgroundColor = [UIColor brownColor];
            [self.view addSubview:imageGrid];
        } else {
            UIImageView *imageGrid = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, 40, 40)];
            imageGrid.backgroundColor = [UIColor greenColor];
            [self.view addSubview:imageGrid];
        }
        x+=40;
        if (x==320) {
            x=0;
            y+=40;
        }
    }
    x=0;
    y=40;
    for (int i=0; i<16; i++) {
        if (x<=280 && x>=0 && y==40) {
            UIImageView *imageCastle = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, 40, 40)];
            imageCastle.image = [UIImage imageNamed:@"battlement.png"];
            [self.view addSubview:imageCastle];
        } else if (x<=280 && x>160 && y==80) {
            UIImageView *imageCastle = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, 40, 40)];
            imageCastle.image = [UIImage imageNamed:@"wall.png"];
            [self.view addSubview:imageCastle];
        } else if (x<160 && x>=0 && y==80) {
            UIImageView *imageCastle = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, 40, 40)];
            imageCastle.image = [UIImage imageNamed:@"wall.png"];
            [self.view addSubview:imageCastle];
        } else if (x==160 && y==80) {
            UIImageView *imageCastle = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, 40, 40)];
            imageCastle.image = [UIImage imageNamed:@"gate.png"];
            [self.view addSubview:imageCastle];
        }
        x+=40;
        if (x==320) {
            x=0;
            y+=40;
        }
    }
    timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(gameTime) userInfo:nil repeats:YES];
    [super viewDidLoad];
}

- (void)viewDidUnload
{
    [self setButton1:nil];
    [self setButton2:nil];
    [self setButton3:nil];
    [self setButton4:nil];
    [self setInfo:nil];
    [self setLabelGold:nil];
    [self setLivesLeft:nil];
    [self setWaves:nil];
    [self setLabelMonstersRemaining:nil];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

-(void)gameTime {
    if (waveActive==TRUE && gameOver==FALSE) {
//Timer logic
        timerValue += 0.05;
        
//Monster Creation
        if (firstMonster==TRUE) {
            labelMonstersRemaining.text = [NSString stringWithFormat:@"Monsters remaining: %d",monstersRemaining];
            NSLog(@"First monster");
            firstMonster = FALSE;
            nextMonster = timerValue+spawnInterval;
            monster *newMonster = [[monster alloc] init];
            newMonster.health = wave*4;
            newMonster.xcoord = 260;
            newMonster.ycoord = 380;
            newMonster.speed = 5;
            newMonster.slowTimer = 0;
            newMonster.isDead = FALSE;
            newMonster.direction = @"up";
            UIImageView *newMonsterImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"monster.png"]];
            newMonsterImage.frame = CGRectMake(260, 400, 40, 40);
            [monsters addObject:newMonster];
            [monsterImages addObject:newMonsterImage];
            [self.view addSubview:newMonsterImage];
            monstersCreated++;
        }
        int targetMonster;
        if (monstersRemaining>=50) {
            targetMonster = 50;
        } else {
            targetMonster = (wave*3)+5;
        }
        if (timerValue>=nextMonster-0.02 && timerValue<=nextMonster+0.02 && monstersCreated<targetMonster) {
            nextMonster = timerValue+spawnInterval;
            monster *newMonster = [[monster alloc] init];
            newMonster.health = wave*4;
            newMonster.xcoord = 260;
            newMonster.ycoord = 380;
            newMonster.speed = 5;
            newMonster.slowTimer = 0;
            newMonster.isDead = FALSE;
            newMonster.direction = @"up";
            UIImageView *newMonsterImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"monster.png"]];
            newMonsterImage.frame = CGRectMake(260, 400, 40, 40);
            [monsters addObject:newMonster];
            [monsterImages addObject:newMonsterImage];
            [self.view addSubview:newMonsterImage];
            monstersCreated++;
        }
        
//Monster Movement and life loss logic
        for (int i=0; i<monsters.count; i++) {
            monster *currentMonster = [monsters objectAtIndex:i];
            UIImageView *currentMonsterImage = [monsterImages objectAtIndex:i];
            if (currentMonster.isDead==FALSE) {
                if (timerValue>=currentMonster.slowTimer-0.02 && timerValue<=currentMonster.slowTimer+0.02) {
                    currentMonster.speed = 5;
                }
                
                //TODO Water slows
                
                if (currentMonster.direction==@"up") {
                    currentMonster.ycoord -= currentMonster.speed;
                } else if (currentMonster.direction==@"left") {
                    currentMonster.xcoord -= currentMonster.speed;
                } else if (currentMonster.direction==@"right") {
                    currentMonster.xcoord += currentMonster.speed;
                }
                currentMonsterImage.center = CGPointMake(currentMonster.xcoord, currentMonster.ycoord);
                if (currentMonster.xcoord==260 && currentMonster.ycoord<=340 && currentMonster.ycoord>=330) {
                    currentMonster.direction = @"left";
                } else if (currentMonster.xcoord<=100 && currentMonster.xcoord>=90 && currentMonster.ycoord==340) {
                    currentMonster.direction = @"up";
                } else if (currentMonster.xcoord<=100 && currentMonster.xcoord>=90 && currentMonster.ycoord<=220 && currentMonster.ycoord>=210) {
                    currentMonster.direction = @"right";
                } else if (currentMonster.xcoord>=180 && currentMonster.xcoord<=190 && currentMonster.ycoord<=220 && currentMonster.ycoord>=210) {
                    currentMonster.direction = @"up";
                } else if (currentMonster.xcoord>=180 && currentMonster.xcoord<=190 && currentMonster.ycoord<=120) {
                    currentMonster.health = 0;
                    currentMonster.isDead = TRUE;
                    currentMonsterImage.hidden = TRUE;
                    lives--;
                    monstersRemaining--;
                    livesLeft.text = [NSString stringWithFormat:@"Lives: %d",lives];
                    labelMonstersRemaining.text = [NSString stringWithFormat:@"Monsters remaining: %d",monstersRemaining];
                    if (lives==0) {
                        for (int i=0; i<towers.count; i++) {
                            tower *currentTower = [towers objectAtIndex:i];
                            currentTower.projectileImage.hidden = TRUE;
                        }
                        gameOver = TRUE;
                    } else {
                        if (monstersRemaining==0) {
                            for (int i=0; i<towers.count; i++) {
                                tower *currentTower = [towers objectAtIndex:i];
                                currentTower.projectileImage.hidden = TRUE;
                            }
                            wave++;
                            lives++;
                            livesLeft.text = [NSString stringWithFormat:@"Lives: %d",lives];
                            waves.text = [NSString stringWithFormat:@"Wave: %d",wave];
                            waveActive = FALSE;
                            firstMonster = TRUE;
                            monstersRemaining = (wave*3)+5;
                            if (monstersRemaining>=50) {
                                monstersRemaining = 50;
                            }
                            labelMonstersRemaining.text = [NSString stringWithFormat:@"Monsters remaining: %d",monstersRemaining];
                            monstersCreated = 0;
                            button4.hidden = FALSE;
                            if (spawnInterval>=0.50) {
                                spawnInterval -= 0.10;
                            }
                        }
                    }
                }
                
//TODO Tower firing logic
                for (int i=0; i<towers.count; i++) {
                    tower *currentTower = [towers objectAtIndex:i];
                    UIImageView *currentTowerImage = [towerImages objectAtIndex:i];
                    if (currentTower.enabled==TRUE) {
                        if (currentTower.isOnCooldown==FALSE) {
                            if (currentTower.targetedMonster!=nil) {
                                UIImageView *newProjectile = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@Projectile",currentTower.type]]];
                                newProjectile.frame = CGRectMake(currentTowerImage.center.x, currentTowerImage.center.y, 30, 30);
                                currentTower.isOnCooldown = TRUE;
                                currentTower.cooldownTime = timerValue+currentTower.firingSpeed;
                                currentTower.projectileImage = newProjectile;
                                [self.view addSubview:newProjectile];
                            } else if ((currentMonsterImage.center.x>=currentTowerImage.center.x-80 && currentMonsterImage.center.x<=currentTowerImage.center.x+80) && (currentMonsterImage.center.y>=currentTowerImage.center.y-80 && currentMonsterImage.center.y<=currentTowerImage.center.y+80)) {
                                UIImageView *newProjectile = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@Projectile",currentTower.type]]];
                                newProjectile.frame = CGRectMake(currentTowerImage.center.x, currentTowerImage.center.y, 30, 30);
                                currentTower.isOnCooldown = TRUE;
                                currentTower.cooldownTime = timerValue+currentTower.firingSpeed;
                                currentTower.projectileImage = newProjectile;
                                currentTower.targetedMonster = currentMonster;
                                currentTower.targetedMonsterImage = currentMonsterImage;
                                [self.view addSubview:newProjectile];
                            } else {
                                currentTower.targetedMonster = nil;
                                currentTower.projectileImage.hidden = TRUE;
                                
                            }
                        } else {
//Tower projectile targeting
                            if (currentTower.cooldownTime>=timerValue-0.02 && currentTower.cooldownTime<=timerValue+0.02) {
                                currentTower.projectileImage.hidden = TRUE;
                                currentTower.isOnCooldown = FALSE;
                            }
                            if (currentTower.targetedMonster==nil) {
                                currentTower.projectileImage.hidden = TRUE;
                            } else {
                                float projectileSpeedX, projectileSpeedY;
                                if (currentTower.projectileImage.center.x>currentTower.targetedMonsterImage.center.x)
                                    projectileSpeedX = -5;
                                else if (currentTower.projectileImage.center.x<currentTower.targetedMonsterImage.center.x)
                                    projectileSpeedX = 5;
                                else if (currentTower.projectileImage.center.x==currentTower.targetedMonsterImage.center.x)
                                    projectileSpeedX = 6;
                                if (currentTower.projectileImage.center.y>currentTower.targetedMonsterImage.center.y)
                                    projectileSpeedY = -5;
                                else if (currentTower.projectileImage.center.y<currentTower.targetedMonsterImage.center.y)
                                    projectileSpeedY = 5;
                                else if (currentTower.projectileImage.center.y==currentTower.targetedMonsterImage.center.y)
                                    projectileSpeedY = 6;
                                currentTower.projectileImage.center = CGPointMake(currentTower.projectileImage.center.x+projectileSpeedX, currentTower.projectileImage.center.y+projectileSpeedY);
                            
//Tower projectile+monster collision
                                if (CGRectIntersectsRect(currentTower.projectileImage.frame, currentTower.targetedMonsterImage.frame) && currentTower.projectileImage.hidden!=TRUE) {
                                    currentTower.projectileImage.hidden = TRUE;
                                    currentTower.targetedMonster.health -= currentTower.damage;
                                    if (currentTower.type==@"water") {
                                        currentTower.targetedMonster.speed = 3;
                                        currentTower.targetedMonster.slowTimer = timerValue+1.50;
                                    }
                                }
                                if (currentTower.targetedMonster.health<=0 && currentTower.targetedMonster.isDead==FALSE) {
                                    currentTower.projectileImage.hidden = TRUE;
                                    currentTower.targetedMonster.isDead = TRUE;
                                    currentTower.targetedMonsterImage.hidden = TRUE;
                                    currentTower.targetedMonster = nil;
                                    currentTower.targetedMonsterImage = nil;
                                    monstersRemaining--;
                                    gold += 5*wave;
                                    labelGold.text = [NSString stringWithFormat:@"%d",gold];
                                    labelMonstersRemaining.text = [NSString stringWithFormat:@"Monsters remaining: %d",monstersRemaining];
                                    if (monstersRemaining==0) {
                                        livesLeft.text = [NSString stringWithFormat:@"Lives: %d",lives];
                                        wave++;
                                        lives++;
                                        livesLeft.text = [NSString stringWithFormat:@"Lives: %d",lives];
                                        waves.text = [NSString stringWithFormat:@"Wave: %d",wave];
                                        waveActive = FALSE;
                                        firstMonster = TRUE;
                                        monstersRemaining = (wave*3)+5;
                                        if (monstersRemaining>=50) {
                                            monstersRemaining = 50;
                                        }
                                        labelMonstersRemaining.text = [NSString stringWithFormat:@"Monsters remaining: %d",monstersRemaining];
                                        monstersCreated = 0;
                                        button4.hidden = FALSE;
                                        if (spawnInterval>=0.55/*extra 0.05 for margin of error*/) {
                                            spawnInterval -= 0.10;
                                        }
                                    }
                                } else if (currentTower.targetedMonster.isDead==TRUE) {
                                    currentTower.targetedMonster = nil;
                                    currentTower.projectileImage.hidden = TRUE;
                                }
                            }
                        }
                    }
                }
            }
        }
    } else if (gameOver==TRUE) {
        waveActive = FALSE;
        waveShouldBeActive = FALSE;
        controllerGameOver = [self.storyboard instantiateViewControllerWithIdentifier:@"viewGameOver"];
        [self presentModalViewController:controllerGameOver animated:YES];
    }
}

-(void)buttonPress:(id)sender {
//Activates when a gridpoint is tapped
    
//Red indicator logic
    UIButton *button = sender;
    cG = button.tag;
    oldTile.hidden = TRUE;
    float x = [(NSNumber *)[xcoord objectAtIndex:cG] floatValue];
    float y = [(NSNumber *)[ycoord objectAtIndex:cG] floatValue];
    UIImageView *newTile = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, 40, 40)];
    newTile.backgroundColor = [UIColor redColor];
    oldTile = newTile;
    if (cG != 4 && cG != 12 && cG != 20 && cG != 19 && cG != 18 && cG != 26 && cG != 34 && cG != 42 && cG != 43 && cG != 44 && cG != 45 && cG != 46 && cG != 54) {
        [self.view addSubview:oldTile];
    }

//Tower detection logic
//Checks to see if the current gridpoint is a grass tile
    if (cG != 4 && cG != 12 && cG != 20 && cG != 19 && cG != 18 && cG != 26 && cG != 34 && cG != 42 && cG != 43 && cG != 44 && cG != 45 && cG != 46 && cG != 54) {
        if (towers.count!=0) {
//Checks to see if there is a tower at the current gridpoint
            for (int i=0; i<towers.count; i++) {
                tower *currentTower = [towers objectAtIndex:i];
                if (currentTower.gridpoint==cG && currentTower.enabled==TRUE) {
                    towerIsAtCurrentGridpoint = TRUE;
                    towerIndex=i;
                } else {
                }
            }
            if (towerIsAtCurrentGridpoint==TRUE) {
                tower *currentTower = [towers objectAtIndex:towerIndex];
                towerType = currentTower.type;
                NSLog(@"%@",towerType);
                oldTower.hidden = TRUE;
                float x = [(NSNumber *)[xcoord objectAtIndex:cG] floatValue];
                float y = [(NSNumber *)[ycoord objectAtIndex:cG] floatValue];
                UIImageView *newTowerImage = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, 40, 40)];
                newTowerImage.image = [UIImage imageNamed:currentTower.imageName];
                oldTower = newTowerImage;
                if (cG != 4 && cG != 12 && cG != 20 && cG != 19 && cG != 18 && cG != 26 && cG != 34 && cG != 42 && cG != 43 && cG != 44 && cG != 45 && cG != 46 && cG != 54) {
                    [self.view addSubview:oldTower];
                }
                
                towerIsAtCurrentGridpoint = FALSE;
                info.text = currentTower.name;
//Main button changes (upgrade button is hidden for now)
                button1.hidden = TRUE;
                [button1 setTitle:@"Upgrade" forState:UIControlStateNormal];
                button1.tag = 71;
                button2.hidden = FALSE;
                button2.tag = 72;
                button2.titleLabel.textAlignment = UITextAlignmentCenter;
                [button2.titleLabel setLineBreakMode:UILineBreakModeCharacterWrap];
                [button2 setTitle:@"Sell\n50g" forState:UIControlStateNormal];
                button3.hidden = FALSE;
                [button3 setTitle:@"Stats" forState:UIControlStateNormal];
                button3.tag = 73;
            } else {
                info.text = @" ";
                button1.hidden = FALSE;
                [button1 setTitle:@"Build" forState:UIControlStateNormal];
                button1.tag = 61;
                button2.hidden = TRUE;
                button3.hidden = TRUE;
            }
        } else {
            button1.hidden = FALSE;
            [button1 setTitle:@"Build" forState:UIControlStateNormal];
            button1.tag = 61;
            button2.hidden = TRUE;
            button3.hidden = TRUE;
        }
    } else {
//Hides buttons if a dirt tile is tapped
        button1.hidden = TRUE;
        button2.hidden = TRUE;
        button3.hidden = TRUE;
    }
}

- (IBAction)pause:(id)sender {
    if (waveActive==TRUE) {
        waveShouldBeActive = TRUE;
        waveActive = FALSE;
    }
    controllerPause = [self.storyboard instantiateViewControllerWithIdentifier:@"viewPause"];
    [self presentModalViewController:controllerPause animated:YES];
}

- (IBAction)mainButtons:(id)sender {
    UIButton *button = sender;
    if (button.tag==61) {
//Build
        if (waveActive==TRUE) {
            waveShouldBeActive = TRUE;
            waveActive = FALSE;
        }
        controllerBuild = [self.storyboard instantiateViewControllerWithIdentifier:@"view2"];
        [self presentModalViewController:controllerBuild animated:YES];
    } else if (button.tag==72) {
//Sell
        tower *myTower = [towers objectAtIndex:towerIndex];
        if (myTower.enabled==TRUE) {
            gold += myTower.sellPrice;
            myTower.enabled = FALSE;
            float x = [(NSNumber *)[xcoord objectAtIndex:cG] floatValue];
            float y = [(NSNumber *)[ycoord objectAtIndex:cG] floatValue];
            UIImageView *newTile = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, 40, 40)];
            newTile.backgroundColor = [UIColor greenColor];
            [self.view addSubview:newTile];
            button1.hidden = TRUE;
            button2.hidden = TRUE;
            button3.hidden = TRUE;
            labelGold.text = [NSString stringWithFormat:@"%d",gold];
            info.text = @" ";
        }
    } else if (button.tag==73) {
//Stats
        if (waveActive==TRUE) {
            waveShouldBeActive = TRUE;
            waveActive = FALSE;
        }
        controllerStats = [self.storyboard instantiateViewControllerWithIdentifier:@"viewStats"];
        [self presentModalViewController:controllerStats animated:YES];
    } else if (button.tag==64) {
//Start
        for (int i=0; i<towers.count; i++) {
            tower *currentTower = [towers objectAtIndex:i];
            currentTower.isOnCooldown = FALSE;
        }
        waveActive = TRUE;
        button4.hidden = TRUE;
    }
}
-(void)viewDidAppear:(BOOL)animated {
    if (waveShouldBeActive==TRUE) {
        waveActive = TRUE;
        waveShouldBeActive = FALSE;
    }
    if (build==TRUE) {
        build = FALSE;
        tower *myTower = [[tower alloc] init];
        if (towerType==@"lightning") {
            myTower.name = @"Lightning Tower";
            myTower.imageName = @"lightningTower.png";
            myTower.damage = 4;
            myTower.sellPrice = 50;
            myTower.special = @" ";
            myTower.type = @"lightning";
            myTower.firingSpeed = 0.80;
        } else if (towerType==@"water") {
            myTower.name = @"Water Tower";
            myTower.imageName = @"waterTower.png";
            myTower.damage = 3;
            myTower.sellPrice = 50;
            myTower.special = @"Slows enemies.";
            myTower.type = @"water";
            myTower.firingSpeed = 1.25;
        } else if (towerType==@"earth") {
            myTower.name = @"Earth Tower";
            myTower.imageName = @"earthTower.png";
            myTower.damage = 7;
            myTower.sellPrice = 50;
            myTower.special = @"Deals AoE damage.";
            myTower.type = @"earth";
            myTower.firingSpeed = 1.00;
        } else if (towerType==@"air") {
            myTower.name = @"Air Tower";
            myTower.imageName = @"airTower.png";
            myTower.damage = 2;
            myTower.sellPrice = 50;
            myTower.special = @"Fast attack speed.";
            myTower.type = @"air";
            myTower.firingSpeed = 0.50;
        }
        myTower.enabled = TRUE;
        myTower.gridpoint = cG;
        myTower.isOnCooldown = FALSE;
        [towers addObject:myTower];
        towerIndex = towers.count-1;
        float x = [(NSNumber *)[xcoord objectAtIndex:cG] floatValue];
        float y = [(NSNumber *)[ycoord objectAtIndex:cG] floatValue];
        UIImageView *newTowerImage = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, 40, 40)];
        newTowerImage.image = [UIImage imageNamed:myTower.imageName];
        [towerImages addObject:newTowerImage];
        [self.view addSubview:newTowerImage];
        
        info.text = myTower.name;
        labelGold.text = [NSString stringWithFormat:@"%d",gold];
        
        towerType = myTower.type;
        NSLog(@"%@",towerType);
        button1.hidden = TRUE;
        [button1 setTitle:@"Upgrade" forState:UIControlStateNormal];
        button1.tag = 71;
        button2.hidden = FALSE;
        button2.tag = 72;
        button2.titleLabel.textAlignment = UITextAlignmentCenter;
        [button2.titleLabel setLineBreakMode:UILineBreakModeCharacterWrap];
        [button2 setTitle:@"Sell\n50g" forState:UIControlStateNormal];
        button3.hidden = FALSE;
        [button3 setTitle:@"Stats" forState:UIControlStateNormal];
        button3.tag = 73;
    }
    if (globalRestart==TRUE) {
        globalRestart = FALSE;
        
        for (int i=0; i<towers.count; i++) {
            tower *currentTower = [towers objectAtIndex:i];
            currentTower.projectileImage.hidden = TRUE;
        }
        for (int i=0; i<towerImages.count; i++) {
            UIImageView *image = [towerImages objectAtIndex:i];
            image.hidden = TRUE;
        }
        for (int i=0; i<monsterImages.count; i++) {
            UIImageView *image = [monsterImages objectAtIndex:i];
            image.hidden = TRUE;
        }
        [towers removeAllObjects];
        [towerImages removeAllObjects];
        [monsters removeAllObjects];
        [monsterImages removeAllObjects];
        build = FALSE;
        globalRestart = FALSE;
        button4.hidden = FALSE;
        [button4 setTitle:@"Start" forState:UIControlStateNormal];
        button4.tag = 64;
        cG = 0;
        spawnInterval = 1.00;
        wave = 1;
        firstMonster = TRUE;
        monstersRemaining = 0;
        button1.hidden = TRUE;
        button2.hidden = TRUE;
        button3.hidden = TRUE;
        towerIsAtCurrentGridpoint = FALSE;
        towerIndex = 0;
        gold = 125;
        lives = 5;
        gameOver = FALSE;
        waveActive = FALSE;
        waveShouldBeActive = FALSE;
        monstersRemaining = 8;
        monstersCreated = 0;
        timerValue = 0;
        nextMonster = 0;
        labelGold.text = [NSString stringWithFormat:@"%d",gold];
        livesLeft.text = [NSString stringWithFormat:@"Lives: %d",lives];
        waves.text = [NSString stringWithFormat:@"Wave: %d",wave];
        labelMonstersRemaining.text = [NSString stringWithFormat:@"Monsters remaining: %d",monstersRemaining];
    }
}
@end
